package com.baibei.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.AttributeSet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 只能输入数字的密码框
 * Created by ChenRui on 2017/8/21 0021 16:50.
 */
public class NumberPasswordEditText extends AppCompatEditText {
    public NumberPasswordEditText(Context context) {
        super(context);
        init();
    }

    public NumberPasswordEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public NumberPasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {
        List<InputFilter> filterList = new ArrayList<>();
        filterList.addAll(Arrays.asList(getFilters()));
        filterList.add(new InputFilter() {
            Pattern mPattern = Pattern.compile("[0-9]");

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                // 删除等特殊字符，直接返回
                if ("".equals(source.toString()) || dstart >= 6) {
                    return null;
                }
                String dValue = source.toString();

                if (!mPattern.matcher(dValue).find()) {
                    return "";
                }
                return null;
            }
        });
        InputFilter[] filters = new InputFilter[filterList.size()];
        setFilters(filterList.toArray(filters));
    }
}
